package cn.rengy.tpa.wxmp.message.subscribemsg;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.http.Consts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

import cn.rengy.tool.http.HttpUtils;
import cn.rengy.tpa.wxmp.exception.WeChatException;
import cn.rengy.tpa.wxmp.token.AccessToken;

/**
 * 一次性订阅消息
 * @author rengy
 * @date   2017年9月21日
 */
public class SubscribeMsg {
	private static Logger logger = LoggerFactory.getLogger(SubscribeMsg.class);
	
	private static final String REDIRECT_URL = "https://mp.weixin.qq.com/mp/subscribemsg?action=get_confirm";
	private static final String MSG_URL="https://api.weixin.qq.com/cgi-bin/message/template/subscribe?access_token=";
	private AccessToken accessToken;
	public SubscribeMsg(AccessToken accessToken) {
		this.accessToken = accessToken;
	}
	/**
	 * 
	 * @param redirect_url 授权后重定向的回调地址
	 * @param reserved 用于保持请求和回调的状态
	 * @param appid
	 * @param scene 0-10000的整形值，用来标识订阅场景值
	 * @param template_id 订阅消息模板ID
	 * @return
	 */
	public static String generateRedirectURL(String redirect_url, String reserved,String appid,int scene,String template_id) {
        StringBuilder url = new StringBuilder(REDIRECT_URL);
        url.append("&appid=").append(appid);
        url.append("&redirect_url=").append(urlEncode(redirect_url));
        url.append("&reserved=").append(urlEncode(reserved));
        url.append("&scene=").append(scene);
        url.append("&template_id=").append(template_id);
        url.append("#wechat_redirect");
        return url.toString();
    }
	public void send(SubscribeMsgRequest subscribeMsgRequest) throws Exception{
		String msgBody=JSONObject.toJSONString(subscribeMsgRequest);
		logger.debug("SubscribeMsgPost:{}",msgBody);
		for(int i=0;i<2;i++){
			String resultStr = HttpUtils.post(MSG_URL+this.accessToken.token(), msgBody);
			logger.debug("SubscribeMsgResult:{}",resultStr);
			JSONObject jsonObject = JSONObject.parseObject(resultStr);
			int errCode =jsonObject.getIntValue("errcode");
			if(errCode==0){
				break;
			}else if(errCode==40001){
				this.accessToken.refresh();
			}else{
				String errmsg=jsonObject.getString("errmsg");
				throw new WeChatException(errCode,errmsg);
			}
		}
	}
	private static String urlEncode(String str) {
        String result = str;
        try {
        	if(str!=null){
        		result = URLEncoder.encode(str, Consts.UTF_8.name());
        	}
        } catch (UnsupportedEncodingException e) {
            // never throws
        }
        return result;
    }
}
